package com.example.elemui_demo.utils;



import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AESUtils {



    /*
     * 加密用的Key 可以用26个字母和数字组成，最好不要用保留字符，虽然不会错，至于怎么裁决，个人看情况而定
     * 此处使用AES-128-CBC加密模式，key需要为16位。
     */
    private static final String SKEY = "Hlkj@~_^&&123_78";

    // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
    private static final String IVSTR = "0201080306050704";


    /**
     *  加密
     * @Title: Encrypt
     * @Description: TODO
     * @param sSrc
     * @return
     * @return: String
     */
    public static String Encrypt( String sSrc ){
        try{
            if(sSrc==null || sSrc.length()<2){
                return null;
            }
            if( SKEY == null ) {
                System.out.print( "Key为空null" );
                return null;
            }
            // 判断Key是否为16位
            if( SKEY.length() != 16 ) {
                System.out.print( "Key长度不是16位" );
                return null;
            }
            byte[] raw = SKEY.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec( raw, "AES" );
            Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" );// "算法/模式/补码方式"
            IvParameterSpec iv = new IvParameterSpec( IVSTR.getBytes() );// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init( Cipher.ENCRYPT_MODE, skeySpec, iv );
            byte[] encrypted = cipher.doFinal( sSrc.getBytes("utf-8") );

            return ObjectSerializer.encodeBytes( encrypted );
        }catch(Exception ex){
            return null;
        }

    }
    /**
     *  加密
     * @Title: Encrypt
     * @Description: TODO
     * @param sSrc
     * @return
     * @return: String
     */
    public static String Encrypt2( String sSrc,String SKEY,String IVSTR){
        try{
            if(sSrc==null || sSrc.length()<2){
                return null;
            }
            if( SKEY == null ) {
                System.out.print( "Key为空null" );
                return null;
            }
            // 判断Key是否为16位
            if( SKEY.length() != 16 ) {
                System.out.print( "Key长度不是16位" );
                return null;
            }
            byte[] raw = SKEY.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec( raw, "AES" );
            Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" );// "算法/模式/补码方式"
            IvParameterSpec iv = new IvParameterSpec( IVSTR.getBytes() );// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init( Cipher.ENCRYPT_MODE, skeySpec, iv );
            byte[] encrypted = cipher.doFinal( sSrc.getBytes("utf-8") );

            return ObjectSerializer.encodeBytes( encrypted );
        }catch(Exception ex){
            return null;
        }

    }
    /**
     *  解密
     * @Title: Decrypt
     * @Description: TODO
     * @param sSrc
     * @return
     * @return: String
     */
    public static String Decrypt( String sSrc){
        try {
            // 判断Key是否正确
            if(sSrc==null || sSrc.length()<16){
                return null;
            }
            if( SKEY == null ) {
                System.out.print( "Key为空null" );
                return null;
            }
            // 判断Key是否为16位
            if( SKEY.length() != 16 ) {
                System.out.print( "Key长度不是16位" );
                return null;
            }
            byte[] raw = SKEY.getBytes( "ASCII" );
            SecretKeySpec skeySpec = new SecretKeySpec( raw, "AES" );
            Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" );
            IvParameterSpec iv = new IvParameterSpec( IVSTR.getBytes() );
            cipher.init( Cipher.DECRYPT_MODE, skeySpec, iv );

            byte[] encrypted1 = ObjectSerializer.decodeBytes( sSrc );
            try {
                byte[] original = cipher.doFinal( encrypted1 );
                String originalString = new String( original,"UTF-8");
                return originalString;
            }
            catch( Exception e ) {
                System.out.println( e.toString() );
                return null;
            }
        }
        catch(Exception ex ) {
            return null;
        }
    }


    public static String CustomDecrypt( String sSrc, String key, String ivstr){
        try {
            // 判断Key是否正确
            if(sSrc==null || sSrc.length()<16){
                return null;
            }
            if( key == null ) {
                System.out.print( "Key为空null" );
                return null;
            }
            // 判断Key是否为16位
            if( key.length() != 16 ) {
                System.out.print( "Key长度不是16位" );
                return null;
            }
            byte[] raw = key.getBytes( "ASCII" );
            SecretKeySpec skeySpec = new SecretKeySpec( raw, "AES" );
            Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" );
            IvParameterSpec iv = new IvParameterSpec( ivstr.getBytes() );
            cipher.init( Cipher.DECRYPT_MODE, skeySpec, iv );

            byte[] encrypted1 = ObjectSerializer.decodeBytes( sSrc );
            try {
                byte[] original = cipher.doFinal( encrypted1 );
                String originalString = new String( original,"UTF-8");
                return originalString;
            }
            catch( Exception e ) {
                System.out.println( e.toString() );
                return null;
            }
        }
        catch(Exception ex ) {
            return null;
        }
    }

    /**
     * 2020双十一办理业务添加能量方法
     * @param phoneNum 手机号码
     * @param type 业务类型
     */
    public static void addEnergy(String phoneNum, String type) {
        String params = phoneNum + "&" + type;
        JSONObject jo = new JSONObject();
        JSONObject j1 = new JSONObject();
        j1.put("params", params);
        JSONObject j2 = new JSONObject();
        j2.put("mac", AESUtils.Encrypt(params));
        jo.put("sec", j2);
        jo.put("in", j1);
        //入参
        String inParams = jo.toString();
        //使用httpclient调用接口
        AESUtils.httpClientPost(inParams);
    }

    public static void httpClientPost(String inParams) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost("https://ah.189.cn/netup/doubleelvenactive/businessSuccess");
//        HttpPost httpPost = new HttpPost("http://127.0.0.1:7002/netup/doubleelvenactive/businessSuccess");

        StringEntity entity = new StringEntity(inParams, "UTF-8");

        httpPost.setHeader("user-agent", "Mozilla/5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] s) {
//       String usd = Encrypt("18019905133&4");
//       System.out.print("加密后的字段："+usd);
//        addEnergy("18019905133","4");
//        addEnergy("19965102380","4");
//        addEnergy("18656558187","4");
//        addEnergy("18019905133","4");
//        addEnergy("17856698156","4");
//        addEnergy("18119642738","3");


        //DOUBLE11_2020_
        String uphone = "15305603979";
        String url = "https://ah.189.cn/qy/cms/html/11activity.html?";
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddHHmmss");
        String encrypt = MD5.md5for32("30000" + uphone + "weixin" + ft.format(new Date())).toUpperCase();
        String jmlj = "cha=30000&activitySource=wapKdDouble11&activityType=" + 5 + "&phone=" + uphone + "&time=" + ft.format(new Date()) + "&encrypt=" + encrypt;
        System.err.println(url + jmlj);
    }
}

